from rediscluster.client import RedisCluster
import datetime
import sys

import threading
import json

debug_mode = True


class RedisClusterClient(object):
    instance = None

    @staticmethod
    def init_redis_cluster_connection():
        redis_nodes = [
            {'host': '172.16.200.35', 'port': 6379},
            {'host': '172.16.200.36', 'port': 6379},
            {'host': '172.16.200.37', 'port': 6379},
            {'host': '172.16.200.38', 'port': 6379},
            {'host': '172.16.200.39', 'port': 6379},
            {'host': '172.16.200.40', 'port': 6379}
        ]

        try:
            threadLock = threading.Lock()
            threadLock.acquire()

            if RedisClusterClient.instance is None:
                RedisClusterClient.instance = RedisCluster(startup_nodes=redis_nodes)

            threadLock.release()

        except Exception as err:
            print(err)
            sys.exit(1)
        else:
            print("RedisClusterClient.instance init ok")

    @staticmethod
    def get_cop_num(user_id):
        b_show_num_dict = RedisClusterClient.instance.hgetall("copShowNumMap:" + user_id)
        if debug_mode:
            for k in b_show_num_dict.keys():
                print(k.decode('utf-8') + " : " + b_show_num_dict[k].decode('utf-8') + "\n")

    @staticmethod
    def get_last_call_info(key):
        b_last_call_info_dict = RedisClusterClient.instance.hgetall(key)
        if debug_mode:
            for k in b_last_call_info_dict.keys():
                print(k.decode('utf-8') + " : " + b_last_call_info_dict[k].decode('utf-8') + "\n")
                if b_last_call_info_dict[k] is dict:
                    for kk in b_last_call_info_dict[k].keys():
                        print(kk.decode('utf-8') + " : " + b_last_call_info_dict[k][kk].decode('utf-8') + "\n")


RedisClusterClient.init_redis_cluster_connection()

if __name__ == '__main__':

    #
    # 创建两个线程

    try:
        t1 = threading.Thread(target=RedisClusterClient.get_cop_num, kwargs={"user_id": "20358"})
        t2 = threading.Thread(target=RedisClusterClient.get_last_call_info, kwargs={"key": "LastCallInfo:02023398853:13724059427"})
        t1.start()
        t2.start()
        t1.join()
        t2.join()

    except Exception as err:
        print(err)
        "Error: unable to start thread"

    print("over")
